import React, { useCallback } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import { View, Image, Swiper, SwiperItem } from '@tarojs/components';
import { connect } from 'react-redux';
import utils from '@/utils/index';
import './index.scss';

const Advert = ({ advert = [], alias = '', dispatch }) => {
  console.log('Advert advert:', advert);
  let { advertList = [], advertInfo = {} } = advert[alias] || {};

  useDidShow(() => {
    getAdvert();
  });

  const getAdvert = () => {
    alias.length > 0 &&
      advert[alias]?.advertInfo?.alias !== alias &&
      dispatch({
        type: 'otherApi/getAdvertModel',
        payload: { alias },
      });
  };

  const goToOtherPageByLink = useCallback((url) => {
    Taro.navigateTo({
      url,
    });
  }, []);

  return (
    <View
      className="AdvertBanner"
      style={{
        width: utils.getSizeByScale(advertInfo.wide) + 'px',
        height: utils.getSizeByScale(advertInfo.high) + 'px',
      }}
    >
      {advertList.length == 1 && (
        <View className="banner">
          <Image
            className="bannerIcon"
            src={advertList[0].imageUrl}
            onClick={() => advertList[0]?.url?.length && goToOtherPageByLink(advertList[0].url)}
          />
        </View>
      )}
      {advertList.length > 1 && (
        <Swiper
          className="banner"
          indicatorColor="rgba(245,245,245,0.5)"
          indicatorActiveColor="#999"
          circular
          indicatorDots
          autoplay
          interval={3000}
          style={{
            width: utils.getSizeByScale(advertInfo.wide) + 'px',
            height: utils.getSizeByScale(advertInfo.high) + 'px',
          }}
        >
          {advertList.length > 0 &&
            advertList.map((ad, index) => (
              <SwiperItem key={'swipicture' + '_' + index}>
                <Image
                  className="bannerIcon"
                  src={ad.imageUrl}
                  key={'swiperImage' + index}
                  onClick={() => ad?.url?.length && goToOtherPageByLink(ad.url)}
                />
              </SwiperItem>
            ))}
        </Swiper>
      )}
    </View>
  );
};

export default connect(({ otherApi }) => ({
  advert: otherApi.advert,
}))(Advert);
